<?php

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\NodeService;
use service\ToolsService;
use think\App;
use think\Db;
use think\Session;

/**
 * 后台入口
 * Class Index
 * @package app\admin\controller
 * @author liuda <1576283429@qq.com>
 * @date 2018/05/10
 */
class Index extends BasicAdmin
{

    /**
     * 后台框架布局
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        NodeService::applyAuthNode();
        $list = (array)Db::name('SystemMenu')->where(['status' => '1'])->order('sort asc,id asc')->select();
        $menus = $this->buildMenuData(ToolsService::arr2tree($list), NodeService::get(), !!session('user'));
        if (empty($menus) && !session('user.id')) {
            $this->redirect('@admin/login');
        }
        return $this->fetch('', ['title' => '系统管理', 'menus' => $menus]);
    }

    /**
     * 后台主菜单权限过滤
     * @param array $menus 当前菜单列表
     * @param array $nodes 系统权限节点数据
     * @param bool $isLogin 是否已经登录
     * @return array
     */
    private function buildMenuData($menus, $nodes, $isLogin)
    {
        foreach ($menus as $key => &$menu) {
            !empty($menu['sub']) && $menu['sub'] = $this->buildMenuData($menu['sub'], $nodes, $isLogin);
            if (!empty($menu['sub'])) {
                $menu['url'] = '#';
            } elseif (preg_match('/^https?\:/i', $menu['url'])) {
                continue;
            } elseif ($menu['url'] !== '#') {
                $node = join('/', array_slice(explode('/', preg_replace('/[\W]/', '/', $menu['url'])), 0, 3));
                $menu['url'] = url($menu['url']) . (empty($menu['params']) ? '' : "?{$menu['params']}");
                if (isset($nodes[$node]) && $nodes[$node]['is_login'] && empty($isLogin)) {
                    unset($menus[$key]);
                } elseif (isset($nodes[$node]) && $nodes[$node]['is_auth'] && $isLogin && !auth($node)) {
                    unset($menus[$key]);
                }
            } else {
                unset($menus[$key]);
            }
        }
        return $menus;
    }

    /**
     * 主机信息显示
     * @return string
     */
    public function main()
    {
        $_version = Db::query('select version() as ver');
        $user = session('user');
        if( !$user['is_admin'] ){ //不是管理员，只能看到自己所属的机器信息

        }

        //本月时间
        $thisMonth = date("Y-m");
        $thisMonthArray = get_day_array($thisMonth,3);
        //上个月时间
        $lastMonth =date('Y-m',strtotime('-1 month'));
        $lastMonthArray = get_day_array($lastMonth,3);

        $thisMonthOrder = $this->getOrderInfo($thisMonthArray);
        $lastMonthOrder = $this->getOrderInfo($lastMonthArray);

        $this->assign('thisMonthOrder', json_encode($thisMonthOrder,TRUE));
        $this->assign('lastMonthOrder', json_encode($lastMonthOrder,TRUE));
        return $this->fetch('');
    }

    /**
     * 修改密码
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function pass()
    {
        if (intval($this->request->request('id')) !== intval(session('user.id'))) {
            $this->error('只能修改当前用户的密码！');
        }
        if ($this->request->isGet()) {
            $this->assign('verify', true);
            return $this->_form('SystemUser', 'user/pass');
        }
        $data = $this->request->post();
        if ($data['password'] !== $data['repassword']) {
            $this->error('两次输入的密码不一致，请重新输入！');
        }
        $user = Db::name('SystemUser')->where('id', session('user.id'))->find();
        if (md5($data['oldpassword']) !== $user['password']) {
            $this->error('旧密码验证失败，请重新输入！');
        }
        if (DataService::save('SystemUser', ['id' => session('user.id'), 'password' => md5($data['password'])])) {
            $this->success('密码修改成功，下次请使用新密码登录！', '');
        }
        $this->error('密码修改失败，请稍候再试！');
    }

    /**
     * 修改资料
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info()
    {
        if (intval($this->request->request('id')) === intval(session('user.id'))) {
            return $this->_form('SystemUser', 'user/form');
        }
        $this->error('只能修改当前用户的资料！');
    }


    /**
     * 获取订单信息
     * @param $timeArray
     * @param array $params
     * @return array
     */
    private function getOrderInfo($timeArray,$params=[]){
        $user = $_SESSION['ta']['user'];   //$user['is_admin']  1为管理员  其余是供应商
        $data = [];
        $year = date("Y");
        foreach ($timeArray as $key => $time){
            $where = ' 1=1 and isback = 0  ';
            $start = $year.'-'.$time." 00:00:00";
            $end = $year.'-'.$time." 23:59:59";
            if($user['is_admin'] == 1){
                $where .=" AND create_at >= '$start'  AND create_at <= '$end' ";
                $sql = " SELECT sum(case when pay_status = 0 then amount else 0 end) as 'totals' from `order` WHERE {$where} ";
            }else{
                $where .=" AND R.create_at >= '$start'  AND R.create_at <= '$end' ";
                $sql = "SELECT sum(case when pay_status = 0 then amount else 0 end) as 'totals' from `order` R LEFT JOIN machine M ON R.machine_no=M.machine_no WHERE  {$where}  AND M.user_id={$user['id']}";
            }
			//var_dump($sql);
			//exit();

            $list = Db::query($sql);
            $totals = 0;
            if(!empty($list[0])){
                $totals = ($list[0]['totals'])/100;
            }
            $data[] = [
                "time" => $time,
                "totals" =>((float)$totals)
                ];
        }
        return $data;
    }

    public function export(){
        $time =  input('time');
        $exportDate = date("Y-m");
        $date = date("Y-m-d");
        if($time == 'thisMonth'){
            $firstday = date('Y-m-01', strtotime($date))." 00:00:00";
            $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day")).' 23:59:59';
        }else{
            $firstday = date('Y-m-01', strtotime("$date -1 month"))." 00:00:00";
            $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day")).' 23:59:59';
        }
        $session = $this->request->session();
        $user = $session['user'];  //$user['is_admin']  1为管理员  其余是供应商
        $where = ' 1 ';
        if( $user['is_admin'] !=1 ){
            $where.=" AND M.user_id={$user['id']} " ;
        }
        $sql = "SELECT
                *
            FROM
                (
                    SELECT
                        R.machine_no,
                        R.area_id,
                        SUM(R.amount) AS totals
                    FROM
                        `order` R left join machine M on R.machine_no=M.machine_no
                    WHERE {$where} and 
                        R.pay_status = 0 and R.create_at >='{$firstday}' and R.create_at <='{$lastday}'
                    GROUP BY
                        R.machine_no
                ) t
            ORDER BY
                t.totals DESC;
            ";
        $data = Db::query($sql);
        $machineData = " select M.machine_no, M.dormitory_num,A.area_name from machine M left join  area A on M.area_id=A.id";
        $machinesList = Db::query($machineData);
        $filename = $exportDate."订单汇总表";
        header( "Content-type:application/vnd.ms-excel" );
        header("Content-Disposition: attachment; filename=" . $filename . ".csv");
        $fp = fopen('php://output', 'w');
        $header = [
            '机器编码', '机器地区', '订单金额(元)', '机器详细地址'
        ];
        $header = self::self_mb_convert_encoding($header);
        fputcsv($fp, $header);
        if(!empty($data)){
            foreach ($data as $key => $val){
                foreach ($machinesList as $k => $v){
                    if($val['machine_no'] == $v['machine_no']) {
                        $data[$key]['address'] = $v['dormitory_num'];
                        $data[$key]['area'] = $v['area_name'];
                    }
                }
                $finalData = [];
                $finalData['machine_no'] = $data[$key]['machine_no'];
                $finalData['area'] = $data[$key]['area'];
                $finalData['amount'] = $data[$key]['totals']/100;
                $finalData['address'] = $data[$key]['address'];
                $finalData = self::self_mb_convert_encoding($finalData);
                fputcsv($fp, $finalData);
            }
        }
        fclose($fp);
        exit();
    }



    public static function self_mb_convert_encoding($data){
        if(is_array($data)){
            foreach ($data as $k => $v){
                $data[$k] = mb_convert_encoding($v,"GBK", "UTF-8");
            }
        }
        if(is_string($data)){
            $data = mb_convert_encoding($data,"GBK", "UTF-8");
        }
        return $data;
    }
}
